//
//  HTSubjectScrollView.swift
//  MagaCore
//
//  Created by MrMessy on 2023/5/4.
//

import SwiftUI
import PKHUD

struct HTSubFullView: View {
	@Binding var var_showSub: Bool
	@Binding var var_open: Bool
	@Binding var var_subState: HTEnumSubtitleState!
	@Binding var var_palyerCurrentTime: Double!
	@Binding var var_delay: Double!
	@Binding var var_subList: [HTSub]?
	@Binding var var_isShowSubTitle: Bool
	@Binding var var_subtitleList: [HTSubtitle]?
  @State var var_pushToFeedback: (() -> Void)!

	@State private var var_langType: HTEnumSubtitleLanguage!
	@State var var_palyerCurrentTimeCallBack: (() -> Void)!
	@State var var_subtitleSeleted = false

	let var_imageNames = ["setting", "translate", "error"]
	let var_titles = ["Adjust Subtitle Time", "Switch Language", "Report Subtitle Time Error"]
	@State var var_showTime = false
	@State var var_showLang = false
	@State var var_selectLangIndex = 0

	var body: some View {
		HStack(alignment: .top, spacing: 0){
			Spacer()
			VStack(alignment: .leading, spacing: 0){
        ZStack(alignment: .topLeading) {
          VStack(alignment: .leading, spacing: 0){
            HStack(alignment: .center, spacing: 0) {
              Button() {
                var_showSub = false
              } label: {
                Image("back_black")
              }.padding(.leading, var_marginLeft)
              Text("Subtitles")
                .ht_commonTextStyle(color: Color(hex: var_darkColor), fontSize: var_h3, weight: .bold)
                .lineLimit(1)
                .padding(.leading, var_marginLeft)
              Spacer()
              Toggle(isOn: $var_open) {
              }
              .onChange(of: var_open, perform: { var_value in
                var_subState = var_value ? .htEnumOpen : .htEnumClose
                UserDefaults.standard.set(var_value ? "1" : "0", forKey: HTConfig.STATIC_userDefaults_isShowSubtitle)
              })
              .toggleStyle(SwitchToggleStyle(tint: Color(hex: var_orangeColor)))
              .frame(width: 44, height: 24)
              .padding(.trailing, var_marginLeft)

            }
            .frame(width: 340, height: 44)
            .padding(.top, 30)
            Spacer()
              .frame(width: 340, height: 1)
              .background(Color(white: 0, opacity: 0.04))
              .padding(.top, 10)

            ForEach(0..<2){ index in
              ht_settingsView(var_imageName: var_imageNames[index], var_title: var_titles[index], var_index: index)
            }
            Button{
              var_pushToFeedback()
            }label:{
              HStack(alignment: .center, spacing: 0){
                Image("error").frame(width: 22, height: 22)
                Text("Report Subtitle Time Error")
                  .ht_commonTextStyle(color: Color(hex: var_darkColor), fontSize: var_h2, weight: .none)
                  .padding(.leading, 10)
              }
              .padding(.leading, var_marginLeft)
              .padding(.top, 30)
            }
          }
          .frame(width: 340, height: UIDevice.ht_screenHeight(), alignment: .top)
          .background(Color(hex: "ffffff"))
          .padding(.leading, var_marginLeft)
          .padding(.trailing, var_marginLeft)

          // 字幕时间调整
          if var_showTime {
            VStack(alignment: .leading, spacing: 0){
              HStack(alignment: .center, spacing: 0) {
                Button() {
                  var_showTime = false
                } label: {
                  Image("back_black")
                }.padding(.leading, var_marginLeft)
                Text("Adjust Subtitle Time")
                  .ht_commonTextStyle(color: Color(hex: var_darkColor), fontSize: var_h3, weight: .bold)
                  .lineLimit(1)
                  .padding(.leading, var_marginLeft)
                Spacer()
              }
              .frame(width: 340, height: 44)
              .padding(.top, 30)
              Spacer()
                .frame(width: 340, height: 1)
                .background(Color(white: 0, opacity: 0.04))
                .padding(.top, 10)
              VStack(alignment: .center, spacing: 0){
                ScrollView(showsIndicators: false) {
                  ScrollViewReader { var_scroll in
                    ForEach(0..<(var_subtitleList ?? []).count, id: \.self) { index in
                      let var_sub = (var_subtitleList ?? [])[index]
                      Text(var_sub.var_text)
                        .ht_commonTextStyle(color: Color(hex: var_sub.var_selected ?? false ? var_orangeColor : var_darkColor), fontSize: var_h4, weight: var_sub.var_selected ?? false ? .bold : .none)
                        .padding(.bottom, 5)
                        .id(index)
                    }
                    .onChange(of: var_palyerCurrentTime, perform: { var_value in
                      for var_index in 0..<(var_subtitleList ?? []).count {
                        let var_sub = var_subtitleList![var_index]
                        var_subtitleList![var_index].var_selected = false
                        //												var_subtitleSeleted = false
                        if var_palyerCurrentTime > var_sub.var_startTime && var_palyerCurrentTime < var_sub.var_endTime {
                          var_subtitleList![var_index].var_selected = true
                          var_scroll.scrollTo(var_index, anchor: .center)
                          break
                        }
                      }
                    })
                  }
                }
                Spacer()
                  .frame(width: 340, height: 1)
                  .background(Color(white: 0, opacity: 0.04))
                HStack(spacing: 60){
                  Button(){
                    var_delay -= 0.5
                    HUD.flash(.label("0.5s delayed \n(Total: \(var_delay ?? 0.0)s advanced)"), delay: 1.0)
                  }label: {
                    Text("-0.5").ht_commonTextStyle(color: Color(hex: var_darkColor), fontSize: 20, weight: .bold)
                  }
                  Button(){
                    var_delay = 0.0
                    HUD.flash(.label("back to original"), delay: 1.0)
                  }label: {
                    Image("reset").frame(width: 44, height: 44)
                  }
                  Button(){
                    var_delay += 0.5
                    HUD.flash(.label("0.5s advanced \n(Total: \(var_delay ?? 0.0)s advanced)"), delay: 1.0)
                  }label: {
                    Text("+0.5").ht_commonTextStyle(color: Color(hex: var_darkColor), fontSize: 20, weight: .bold)
                  }
                }.frame(width: 340, height: 76)
              }
              .padding(.bottom, UIDevice.ht_safeDistanceBottom())
            }
            .frame(width: 340, height: UIDevice.ht_screenHeight(), alignment: .top)
            .background(Color(hex: "ffffff"))
            .padding(.leading, var_marginLeft)
            .padding(.trailing, var_marginLeft)
          }

          // 切换字幕语言
          if var_showLang {
            VStack(alignment: .leading, spacing: 0){
              HStack(alignment: .center, spacing: 0) {
                Button() {
                  var_showLang = false
                } label: {
                  Image("back_black")
                }.padding(.leading, var_marginLeft)
                Text("Switch Language")
                  .ht_commonTextStyle(color: Color(hex: var_darkColor), fontSize: var_h3, weight: .bold)
                  .lineLimit(1)
                  .padding(.leading, var_marginLeft)
                Spacer()

              }
              .frame(width: 340, height: 44)
              .padding(.top, 30)
              Spacer()
                .frame(width: 340, height: 1)
                .background(Color(white: 0, opacity: 0.04))
                .padding(.top, 10)
                .padding(.bottom, 20)
              ScrollView(showsIndicators: false) {
                ForEach(0..<(var_subList ?? []).count, id: \.self) { index in
                  let var_selected = var_selectLangIndex == index
                  let var_item = var_subList![index]
                  Button() {
                    var_selectLangIndex = index
                    HTTools.ht_setSubTitlePreference(var_lang: var_item.var_lang ?? "")
                    ht_analysisSub(var_sub: var_item)
                  } label: {
                    HStack(spacing: 0) {
                      if var_selected {
                        Image("radio")
                          .frame(width: 18, height: 18)
                          .padding(.trailing, 10)
                          .padding(.leading, var_marginLeft)
                      } else {
                        Text("")
                          .frame(width: 18, height: 18)
                          .padding(.trailing, 10)
                          .padding(.leading, var_marginLeft)
                      }
                      Text(var_item.var_lang ?? "")
                        .ht_commonTextStyle(color: Color(hex: var_selected ? var_orangeColor : var_darkColor), fontSize: var_h3, weight: .none)
                      Spacer()
                    }
                    .padding(.top, 20)
                    .padding(.bottom, 20)
                  }
                }
              }.padding(.bottom, 30)
            }
            .frame(width: 340, height: UIDevice.ht_screenHeight(), alignment: .top)
            .background(Color(hex: "ffffff"))
            .padding(.leading, var_marginLeft)
            .padding(.trailing, var_marginLeft)
          }
        }
			}
			.frame(width: 340, height: UIDevice.ht_screenHeight())
			.background(Color(hex: "ffffff"))
		}
    .frame(width: UIDevice.ht_screenWidth(), height: UIDevice.ht_screenHeight())
		.background(Color(white:0, opacity: 0.5))
		.onTapGesture(perform: {
			var_showSub = false
		})
		.onAppear {
			let var_subtitleLang = HTTools.ht_getSubTitlePreference()
			for i in 0..<(var_subList ?? []).count {
				let var_item = var_subList![i]
				if var_item.var_lang == "English" { // 默认英语
					var_selectLangIndex = i
				}
				if var_item.var_lang == var_subtitleLang {
					var_selectLangIndex = i
					break
				}
			}
		}
	}
	
	// 选择字幕设置
	func ht_settingsView(var_imageName: String, var_title: String, var_index: Int) -> some View {
		Button() {
			if var_index == 0 {
				var_showTime = true
			} else if var_index == 1 {
				var_showLang = true
			}
		} label: {
			HStack(alignment: .center, spacing: 0){
				Image(var_imageName).frame(width: 22, height: 22)
				Text(var_title)
					.ht_commonTextStyle(color: Color(hex: var_darkColor), fontSize: var_h2, weight: .none)
					.padding(.leading, 10)
			}
			.padding(.leading, var_marginLeft)
			.padding(.top, 30)
		}
	}
	
	// 切换语言逻辑
	func ht_switchLang() {
    let var_subLangKey = UserDefaults.standard.string(forKey: HTConfig.STATIC_userDefaults_subtitleLang)
    var_subState = var_isShowSubTitle ? .htEnumOpen : .htEnumClose
		
		if var_subLangKey == "1" { // 英语
			for var_sub in var_subList ?? [] {
				if var_sub.var_lang ?? "" == "English" {
					ht_analysisSub(var_sub: var_sub)
					var_delay = var_sub.var_delay ?? 0.0
				}
			}
		} else if var_subLangKey == "2" { // 西班牙
			for var_sub in var_subList ?? [] {
				if var_sub.var_lang ?? "" == "Spanish" {
					ht_analysisSub(var_sub: var_sub)
					var_delay = var_sub.var_delay ?? 0.0
				}
			}
		} else { // 所有
			if (var_subList ?? []).count > 0 {
				ht_analysisSub(var_sub: var_subList!.first ?? HTSub())
				var_delay = var_subList!.first?.var_delay ?? 0.0
			} else {
        var_subState = .htEnumDisable
			}
		}
	}
	
	// 解析字幕
 func ht_analysisSub(var_sub: HTSub) {
		var_delay = var_sub.var_delay ?? 0.0
		HTTools.ht_unzipFile(url: var_sub.var_sub ?? "") { var_subtitles in
			var_subtitleList = var_subtitles
		} andFail: {
		}
	}
}
